/**
 * 获取uuid
 */
export function getUUID() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
    return (c === 'x' ? (Math.random() * 16) | 0 : 'r&0x3' | '0x8').toString(16)
  })
}
export function treeDataTranslate(data, id = 'id', pid = 'parentId') {
  var res = []
  var temp = {}
  for (var i = 0; i < data.length; i++) {
    temp[data[i][id]] = data[i]
  }
  for (var k = 0; k < data.length; k++) {
    if (temp[data[k][pid]] && data[k][id] !== data[k][pid]) {
      if (!temp[data[k][pid]]['children']) {
        temp[data[k][pid]]['children'] = []
      }
      if (!temp[data[k][pid]]['_level']) {
        temp[data[k][pid]]['_level'] = 1
      }
      data[k]['_level'] = temp[data[k][pid]]._level + 1
      temp[data[k][pid]]['children'].push(data[k])
    } else {
      res.push(data[k])
    }
  }
  return res
}

// 时间日期转换
export const formatDate = function (date, fmt = 'yyyy-MM-dd') {
  date = new Date(date)
  var o = {
    'M+': date.getMonth() + 1, //月份
    'd+': date.getDate(), //日
    'h+': date.getHours(), //小时
    'm+': date.getMinutes(), //分
    's+': date.getSeconds(), //秒
    'q+': Math.floor((date.getMonth() + 3) / 3), //季度
    S: date.getMilliseconds() //毫秒
  }
  if (/(y+)/.test(fmt))
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  for (var k in o)
    if (new RegExp('(' + k + ')').test(fmt))
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length)
      )
  return fmt
}

// 优化对象
export const purifyOb = (ob) => {
  const result = {}
  for (let key in ob) {
    if (ob[key] !== undefined && ob[key] !== '' && ob[key] !== []) {
      result[key] = ob[key]
    }
  }
  return result
}
//计算高度
export const getTableHeight = (subtract) => {
  return document.body.clientHeight - subtract
}
// 0 ~ num 的随机数
export const randomRange = (start, end) => {
  return Math.floor(Math.random() * (end - start + 1)) + start
}

//  截取url参数
export function getRequest(parName) {
  var str = parName.toLowerCase() + '='
  var gvalue = ''
  var HREF = location.href
  var upperHREF = location.href.toLowerCase()
  if (upperHREF.indexOf(str) > 0) {
    gvalue = HREF.substring(upperHREF.indexOf(str) + str.length, upperHREF.length)
    if (gvalue.indexOf('&') > 0) gvalue = gvalue.substring(0, gvalue.indexOf('&'))
    if (gvalue.indexOf('#') > 0) gvalue = gvalue.split('#')[0]
    gvalue = decodeURIComponent(gvalue)
  }
  return gvalue
}
//防抖(一直触发不会执行)
export function _debounce(func, delay = 300, immediate = false) {
  let timer = null
  return function () {
    if (timer) {
      clearTimeout(timer)
    }
    if (immediate && !timer) {
      func.apply(this, arguments)
    }
    timer = setTimeout(() => {
      func.apply(this, arguments)
    }, delay)
  }
}
//节流（一段时间执行一次）
export function _throttle(fn, delay) {
  let lastime, start
  return function () {
    let that = this
    let args = arguments
    let event = that.event
    that.event = event
    if (!start) {
      fn.apply(that, args)
      start = true
      lastime = Date.now()
    } else {
      if (Date.now() - lastime >= delay) {
        fn.apply(that, args)
        lastime = Date.now()
      }
    }
  }
}
//数据扁平化
export function Flatten(node) {
  let result = []
  let _getNode = function (node) {
    let tmp = JSON.parse(JSON.stringify(node))
    delete tmp.children
    result.push(tmp) //移除拍平数组的子元素,只保留节点相干元素
    let child = node.children
    if (child != undefined && child.length > 0) {
      child.forEach((ele) => {
        // arguments.callee(ele) //由于严格模式下无法使用
        _getNode(ele) //使用此句
      })
    }
  }
  _getNode(node)
  _getNode = null
  return result
}

export function loadJs(src) {
  return new Promise((resolve, reject) => {
    let script = document.createElement('script')
    script.type = 'text/javascript'
    script.onload = () => {
      resolve()
    }
    script.onerror = () => {
      reject()
    }
    script.src = src

    document.getElementsByTagName('body')[0].appendChild(script)
  })
}
//树结构转换(排除结构树中的标签)
export function getTreeData(data) {
  for (let i = 0; i < data.length; i++) {
    if (!data[i].children || data[i].children.length < 1 || data[i].isDirLeaf === 1) {
      // child若为空数组，则将child设为undefined
      data[i].children = undefined
    } else {
      // child若不为空数组，则继续 递归调用 本方法
      getTreeData(data[i].children)
    }
  }
  return data
}
//数据拍平
export function collect(arr) {
  var ret = []
  for (var i = 0; i < arr.length; ++i) {
    var item = arr[i]
    ret.push({ id: item.id, name: item.name })
    if (item.children instanceof Array) {
      ret.push.apply(ret, collect(item.children))
    }
  }
  return ret
}
//获取树结构某条数据
export function getTarget(target, data) {
  var obj = {}
  function each(target, data) {
    for (var i = 0; i < data.length; i++) {
      if (data[i].id == target) {
        obj = data[i]
      } else if (data[i].children && data[i].children.length > 0) {
        each(target, data[i].children)
      }
    }
  }
  each(target, data)
  return obj
}
export function clearObj(obj) {
  Object.keys(obj).forEach((key) => {
    if (key !== 'current' && key !== 'size') {
      obj[key] = ''
    }
  })
}
// 截取两个字符串之间的子字符串,返回第一个
export function subStringOne(text, begin, end) {
  var regex
  if (end == '\\n') {
    regex = RegExp(begin + '(.+)?')
  } else regex = RegExp(begin + '([.\\s\\S]+?)' + end)
  try {
    return regex.exec(text)[1].trim()
  } catch (err) {
    return null
  }
}
//下载
export function download(href, title) {
  const a = document.createElement('a')
  a.setAttribute('href', href)
  a.setAttribute('download', title)
  a.click()
}
//从数组对象删除符合条件的某个或多个数组
export function removeFilters(all, fil) {
  let list = JSON.parse(JSON.stringify(all))
  fil.forEach((item) => {
    list = list.filter((items) => items !== item)
  })
  return list
}
//数组找不同
export function arrDifferent(curArr, oldArr) {
  return curArr.filter((v) => oldArr.every((val) => val.name !== v.printerFid))
}
//数组找相同部分
export function arrIdentical(curArr, oldArr) {
  let arr = []
  curArr.forEach((itemx) => {
    oldArr.forEach((itemy) => {
      if (itemx.printerFid === itemy.name) {
        arr.push(itemx)
      }
    })
  })
  return arr
}
//对象数组分组
export function arrayGroupBy(objectArray, property) {
  return objectArray.reduce(function (acc, obj) {
    let key = obj[property]
    if (!acc[key]) {
      acc[key] = []
    }
    acc[key].push(obj)
    return acc
  }, {})
}
//判断是否空对象
export function isEmptyObject(obj) {
  return Object.keys(obj).length === 0 && obj.constructor === Object
}
//kb转换mb
export function mbTransform(size) {
  let kb = 1024
  let unit = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
  let i = Math.floor(Math.log(size) / Math.log(kb))
  // let unit = size < 1024 ? 'KB' : size < 1024*1024 ? 'MB'
  return (size / Math.pow(kb, i)).toPrecision(3) + ' ' + unit[i]
}
//数据类型
export function dataType(data) {
  return Object.prototype.toString.call(data).slice(8, -1).toLowerCase()
}
